package first.endtoend.parse

import first.endtoend.Product
import grails.validation.ValidationException
import org.springframework.transaction.annotation.Transactional

import java.text.SimpleDateFormat

/*
@author A.Olfa
 */

@Transactional
class ParseCSVProductService
{

    def productInstance
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy")

    def parseProducts(String filepath, boolean header)
    {
        println("####################### JE PASSE DANS PARSE PRODUCT #############")
        println("####################### PATH = " + filepath + " #############")
        def parse = new File(filepath).readLines()[1..-1]
        println("####################### APRES FILE #######################")

        def token = ';'

        for (line in parse)
        {
            // create a categoryInstance and specify its properties

            line.splitEachLine(token) { fields ->

                productInstance = new Product(name: fields[0], unity: fields[1], description: fields[3])
                if (!productInstance.validate())
                {
                    throw new ValidationException("Beneficiary is not valid", productInstance.errors)
                }
                productInstance.save()
                if (productInstance.hasErrors())
                    println productInstance.errors

            }

        }
        println("####################### SORTIT PARSE PRODUCT #######################")
    }
}
